<template>
    <view>
        <view class="padding-main">
            <view v-if="detail != null">
                <form @submit="formSubmit" class="form-container">
                    <view v-for="(item, index) in detail" :key="index" class="form-gorup oh">
						<block v-if="plugins_name == 'wallet'">
							<view class="oh">
								<view class="item-base fl margin-top-sm">
									<view>{{$t('user-recharge-detail.user-recharge-detail.ch84a8')}}：{{item.recharge_no}}</view>
									<view>{{$t('user-recharge-detail.user-recharge-detail.7272ia')}}：{{item.money}}</view>
								</view>
							</view>
						</block>
						<block v-else>
							<view class="oh">
								<navigator hover-class="none">
									<image class="goods-image fl radius br margin-right-lg" :src="item.items[0].images" mode="aspectFill"></image>
								</navigator>
								<view class="item-base fl margin-top-sm">
									<view>{{$t('order-detail.order-detail.36op8f')}}：{{item.order_no}}</view>
									<view>{{$t('order-detail.order-detail.x3ge6c')}}：{{item.total_price}}</view>
								</view>
							</view>
						</block>
						<view class="margin-top-main br-t">
							<view class="form-container-upload oh">
								<view v-if="(form_images_list[index] || null) != null && form_images_list[index].length > 0" class="form-upload-data fl margin-top-main">
									<view v-for="(fx, ix) in form_images_list[index]" :key="ix" class="item fl">
										<!--<text class="delete-icon" @tap="upload_delete_event" :data-index="index" :data-ix="ix">x</text>-->
										<image :src="fx" @tap="upload_show_event" :data-index="index" :data-ix="ix" mode="aspectFill" class="padding-xs dis-block"></image>
									</view>
								</view>
								<view v-else class="form-upload-data fl margin-top-main">
									<image class="upload-icon" :src="common_static_url+'upload-icon.png'" mode="aspectFill" @tap="file_upload_event" :data-index="index"></image>
								</view>
							</view>
						</view>
                    </view>
					<block v-if="is_all_up > 0">
						<view class="form-gorup anonymous">
							<text class="cr-grey margin-top-lg">{{$t('fengcheche.pingzheng_ts')}}</text>
						</view>

						<view class="form-gorup form-gorup-submit">
							<button form-type="submit" class="cr-white round text-size" :style="'background:'+diytheme.main_color+';border:1px solid '+diytheme.main_color+';'" type="default" hover-class="none" :disabled="form_button_disabled">{{$t('common.submit')}}</button>
						</view>
					</block>
                </form>
            </view>
            <view v-else>
                <!-- 提示信息 -->
                <component-no-data :propStatus="data_list_loding_status" :propMsg="data_list_loding_msg"></component-no-data>
            </view>
			<!-- #ifdef APP-PLUS -->
			<yk-authpup ref="authpup" type="top" @changeAuth="changeAuth" :permissionID="permissionID"></yk-authpup>
			<!-- #endif -->
        </view>
    </view>
</template>
<script>
    const app = getApp();
	// #ifdef APP-PLUS
	import ykAuthpup from "@/components/yk-authpup/yk-authpup";
	// #endif
    import componentNoData from "@/components/no-data/no-data";
    import componentBottomLine from "@/components/bottom-line/bottom-line";
	import {system_base_info} from "@/common/js/common/common";
    var common_static_url = app.globalData.get_static_url('common');
    export default {
        data() {
            return {
                common_static_url: common_static_url,
                data_list_loding_status: 1,
                data_list_loding_msg: '',
                params: null,
                detail: null,
                editor_path_type: '',
                form_orderid_list: [],
                form_images_list: [],
                form_button_disabled: false,
				is_all_up:1,
				plugins_name:'',
				backurl:'',
				permissionID:'',
				diytheme:null,
				lang_info:null,
				peraction: ''
            };
        },
        components: {
			// #ifdef APP-PLUS
			ykAuthpup,
			// #endif
            componentNoData,
            componentBottomLine
        },
        props: {},

        onLoad(params) {
            //params['goods_id']=9;
            this.setData({
                params: params
            });
			this.init();
        },
        
        onShow() {
            app.globalData.page_event_onshow_handle();
        },

        // 下拉刷新
        onPullDownRefresh() {
            this.init();
        },

        methods: {
			// 加载之前
			init() {
				// 先获取语言基础信息
				system_base_info()
				.then(data=>{
					this.init_before(data)
					.then(()=>{
						this.init_real();
						
						// 显示分享菜单
						app.globalData.page_share_handle();
					});
				});
			},
			
			// 设置本页参数
			init_before(data){
				var self = this;
				return new Promise((resolve, reject) => {
					self.setData({
						lang_info: data.system_lang_info,
						diytheme: data.diytheme,
					});
					/*uni.setNavigationBarTitle({
					    title: data.index_page_title
					});*/
					resolve();
				});
			},
            // 初始化
			init_real() {
			    var self = this;
			    uni.showLoading({
			        title: this.$t('common.loading_in_text'),
			    });
			    this.setData({
			        data_list_loding_status: 1
			    });
			    uni.request({
			        url: app.globalData.get_request_url("index", "index", "bankext"),
			        method: 'POST',
			        data: {
			            ids: this.params.ids,
						business_type: this.params.business_type || ''
			        },
			        dataType: 'json',
			        success: res => {console.log(res);
			            uni.hideLoading();
			            uni.stopPullDownRefresh();
			            if (res.data.code == 0) {
			                var data = res.data.data;
							// 得到订单集合
							var temp_data_list = [];
							var temp_img_list = [];
							var img_t = [];
							var temp_data = res.data.data.data;
							for (var i in temp_data) {
							    temp_data_list.push(temp_data[i].id);
								
								img_t = [];
								if(temp_data[i].pingzheng_img != ''){
									img_t.push(temp_data[i].pingzheng_img);
								}
								temp_img_list.push(img_t);
							}
			                self.setData({
			                    editor_path_type: data.editor_path_type || '',
			                    detail: data.data,
								form_orderid_list:temp_data_list,
								form_images_list:temp_img_list,
			                    data_list_loding_status: 3,
			                    data_list_loding_msg: '',
								is_all_up:data.is_all_up,
								plugins_name: data.plugins_name,
								backurl: data.backurl
			                });
			            } else {
			                self.setData({
			                    data_list_loding_status: 2,
			                    data_list_loding_msg: res.data.msg
			                });
			                if (app.globalData.is_login_check(res.data, self, 'init')) {
			                    app.globalData.showToast(res.data.msg);
			                }
			            }
			        },
			        fail: () => {
			            uni.hideLoading();
			            uni.stopPullDownRefresh();
			            self.setData({
			                data_list_loding_status: 2,
			                data_list_loding_msg: this.$t('common.internet_error_tips')
			            });
			            app.globalData.showToast(this.$t('common.internet_error_tips'));
			        }
			    });
			},

            // 上传图片预览
            upload_show_event(e) {
                var index = e.currentTarget.dataset.index;
                var ix = e.currentTarget.dataset.ix;
				if(app.globalData.is_android())
				{
					var self = this;
					uni.previewImage({
					    current: self.form_images_list[index][ix],
					    urls: self.form_images_list[index],
						longPressActions: {
							itemList: [self.$t('fengcheche.fcctips.t9')],
							success: function(data) {
								// 先关闭预览，否则会遮挡上方权限提醒
								uni.closePreviewImage();
								self.peraction = 'previewImage';
								self.permissionID = 'WRITE_EXTERNAL_STORAGE';
								setTimeout(()=>{
									self.$refs['authpup'].open(self.form_images_list[index][ix]);
								},500);
							},
							fail: function(err) {
								console.log(err.errMsg);
							}
						}
					});
				}else{
					uni.previewImage({
					    current: this.form_images_list[index][ix],
					    urls: this.form_images_list[index]
					});
				}
            },
            
            // 图片删除
            upload_delete_event(e) {
                var index = e.currentTarget.dataset.index;
                var ix = e.currentTarget.dataset.ix;
                var self = this;
                uni.showModal({
                    title: this.$t('common.warm_tips'),
                    content: this.$t('order.order.psi67g'),
                    success(res) {
                        if (res.confirm) {
                            var list = self.form_images_list;
                            list[index].splice(ix, 1);
                            self.setData({
                                form_images_list: list
                            });
                        }
                    }
                });
            },
            
            // 文件上传
            file_upload_event(e) {
            	if(app.globalData.is_android())
				{
					this.permissionID = 'CAMERA';
					setTimeout(()=>{
						this.$refs['authpup'].open(e);
					},500);
            	}else{
					this.file_upload_event_true(e);
            	}
            },
			// #ifdef APP-PLUS
			//用户授权权限后的回调
			changeAuth(e){
				if(this.permissionID == 'WRITE_EXTERNAL_STORAGE')
				{
					if(this.peraction == 'previewImage')
					{
						app.globalData.save_image_by_url(e);
					}else{
						this.file_upload_event_true(e);
					}
				}else{
					// 第一次是摄像头返回，再返回是相册权限，然后才继续执行
					this.peraction = 'fileupload';
					this.permissionID = 'WRITE_EXTERNAL_STORAGE';
					setTimeout(()=>{
						this.$refs['authpup'].open(e);
					},500);
				}
			},
			// #endif
            file_upload_event_true(e) {
                // 数据初始化
                var index = e.currentTarget.dataset.index;
                var temp_list = this.form_images_list;
                var length = this.detail.length;
                for (var i = 0; i < length; i++) {
                    if (temp_list[i] == undefined) {
                        temp_list[i] = [];
                    }
                }
                this.setData({
                    form_images_list: temp_list
                });

                // 处理上传文件
                var self = this;
                uni.chooseImage({
                    count: 1,
                    success(res) {
                        var success = 0;
                        var fail = 0;
                        var length = res.tempFilePaths.length;
                        var count = 0;
                        self.upload_one_by_one(index, res.tempFilePaths, success, fail, count, length);
                    }
                });
            },
            
            // 采用递归的方式上传多张
            upload_one_by_one(index, img_paths, success, fail, count, length) {
                var self = this;
                if ((self.form_images_list[index] || null) == null || self.form_images_list[index].length < 1) {
                    uni.uploadFile({
                        url: app.globalData.get_request_url("index", "ueditor"),
                        filePath: img_paths[count],
                        name: 'upfile',
                        formData: {
                            action: 'uploadimage',
                            path_type: self.editor_path_type
                        },
                        success: function(res) {
                            success++;
                            if (res.statusCode == 200) {
                                var data = typeof res.data == 'object' ? res.data : JSON.parse(res.data);
                                if (data.code == 0 && (data.data.url || null) != null) {
                                    var list = self.form_images_list;
                                    if ((list[index] || null) == null) {
                                        list[index] = [];
                                    }
                                    list[index].push(data.data.url);
                                    self.setData({
                                        form_images_list: list
                                    });
                                } else {
                                    app.globalData.showToast(data.msg);
                                }
                            }
                        },
                        fail: function(e) {
                            fail++;
                        },
                        complete: function(e) {
                            count++;
            
                            // 下一张
                            if (count >= length) {
                                // 上传完毕，作一下提示
                                //app.showToast('上传成功' + success +'张', 'success');
                            } else {
                                // 递归调用，上传下一张
                                self.upload_one_by_one(index, img_paths, success, fail, count, length);
                            }
                        }
                    });
                }
            },
            
            // 表单
            formSubmit(e) {
                // 商品数量
                var length = this.detail.length;
                
                // 图片校验
                if (this.form_images_list.length > 0) {
                    for (var i in this.form_images_list) {
                        if (this.form_images_list[i].length > 1) {
                            app.globalData.showToast(this.$t('fengcheche.pingzheng_up_num'));
                            return false;
                        }
						if (this.form_images_list[i].length == 0) {
						    app.globalData.showToast(this.$t('fengcheche.pingzheng_up_ts'));
						    return false;
						}
                    }
                }
                
                // 表单数据
                var form_data = e.detail.value;
                form_data['order_id'] = JSON.stringify(this.form_orderid_list);
                form_data['images'] = this.form_images_list.length > 0 ? JSON.stringify(this.form_images_list) : '';
                //console.log(form_data);return;
				
				form_data['business_type'] = this.params.business_type || '';
				
                // 提交表单
                var self = this;
                uni.showLoading({
                    title: this.$t('common.processing_in_text')
                });
                self.setData({
                    form_button_disabled: true
                });
                uni.request({
                    url: app.globalData.get_request_url("somesave", "index", "bankext"),
                    method: 'POST',
                    data: form_data,
                    dataType: 'json',
                    success: res => {
                        uni.hideLoading();
                        if (res.data.code == 0) {
                            app.globalData.showToast(res.data.msg, "success");
							var value = self.backurl;
							if (app.globalData.is_tabbar_pages(value)) {
								var temp = value.split('?');
								if(temp.length > 1 && (temp[1] || null) != null)
								{
									value = temp[0];
								}
								setTimeout(function() {
									// 回到订单首页
									uni.switchTab({
									    url: value
									});
								}, 2000);
							} else {
								setTimeout(function() {
									// 回到订单首页
									app.globalData.url_open(value);
								}, 2000);
							}
                        } else {
                            self.setData({
                                form_button_disabled: false
                            });
                            app.globalData.showToast(res.data.msg);
                        }
                    },
                    fail: () => {
                        uni.hideLoading();
                        self.setData({
                            form_button_disabled: false
                        });
                        app.globalData.showToast(this.$t('common.internet_error_tips'));
                    }
                });
            }
        }
    };
</script>
<style>
    @import './bankext.css';
</style>